package com.xzr.hospitalregister.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.config.HttpUrl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/2/2.
 */

public class DialogLastestVersionAppDownload extends DialogFragment implements View.OnClickListener {
    private FlikerProgressBar bar;
    private TextView updateEnd;
    public static final String SAVE_PATH_FATHER = Environment.getExternalStorageDirectory() + File.separator + "PDJHDownload";
    public static final String SAVE_PATH_APK = SAVE_PATH_FATHER + File.separator + "排队叫号";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.dialog_lastest_version_app_download, null);
        initWidget(inflate);
        initData();
        return inflate;
    }

    public void initWidget(View view) {
        bar = (FlikerProgressBar) view.findViewById(R.id.fpb_dialog_lastest_version_app_download_lastestAPK);
        updateEnd = (TextView) view.findViewById(R.id.tv_dialog_lastest_version_app_download_updateEnd);
        updateEnd.setOnClickListener(this);
    }

    public void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(HttpUrl.LASTEST_VERSION_APK_DOWNLOAD).build();///////////////
//                Request request = new Request.Builder().url("https://qd.myapp.com/myapp/qqteam/Androidlite/qqlite_3.6.2.691_android_r109880_GuanWang_537053371_release_10000484.apk").build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;

                        isExistDir(SAVE_PATH_FATHER);
                        try {
                            is = response.body().byteStream();
                            long total = response.body().contentLength();
                            long sum = 0;
                            fos = new FileOutputStream(new File(SAVE_PATH_APK));
                            while ((len = is.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                                sum += len;
                                final int progress = (int) (sum * 100.0 / total);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        bar.setProgress(progress);
                                        if (progress == 100) {
                                            updateEnd.setText("点击安装");
                                        }
                                    }
                                });
                            }
                            fos.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (is != null)
                                    is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                if (fos != null)
                                    fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }

    private void isExistDir(String s) {
        File downloadFile = new File(s);
        if (!downloadFile.exists())
            downloadFile.mkdirs();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_dialog_lastest_version_app_download_updateEnd:
                if ("点击安装".equals(updateEnd.getText().toString())) {
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.fromFile(new File(SAVE_PATH_APK));
                    installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                    installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(installIntent);// 下载完成之后自动弹出安装界面
                }
                break;
        }
    }
}
